<template>
    <rx-layout>
        <div slot="left" width="220" showButton="true">
            <rx-fit>
                <rx-category-treeeditor
                    cat-key="FORM"
                    :statisticConfig="statisticConfig"
                    :edit="true"
                    @handSelect="handSelect"
                    :async="true"
                    v-if="isShowManageTree"
                    :isAdmin="isManageToTree"
                    :checkToDel="true"
                ></rx-category-treeeditor>
            </rx-fit>
        </div>
        <div slot="center" style>
            <rx-fit :isheader="isheader">
                <div slot="toolheader" foldheader="true" foldbtn="false" border="false">
                    <div class="table-operator">
                        <rx-button alias="formCustomAdd" :butn-icon="'plus'" :butn-type="'primary'"
                                   :show-no-right="true" @click="customAdd">{{$ti18('rxList.newBtn','新建')}}
                        </rx-button>
                        <a-button type="primary" v-if="!isAppDevelop && selectedRowKeys.length > 0 " icon="redo"
                                  @click="changeApp('FORM',selectedRows,'pkId','name','appId','categoryId',changeAppId)">
                            {{i18n('list.changeApp','变更应用')}}
                        </a-button>
                        <a-button v-if="selectedRowKeys.length > 0"
                                  type="primary"
                                  icon="switcher" @click="openCategoryDialog">
                            {{$ti18('rxList.changeCategory','切换分类')}}
                        </a-button>
                        <a-dropdown>
                            <a-button style="margin-left: 8px"> {{$ti18('rxList.moreBtn','更多')}}
                                <a-icon type="down"/>
                            </a-button>
                            <a-menu slot="overlay">
                                <a-menu-item key="1" @click="editOne" v-if="editEnable && selectedRowKeys.length > 0"
                                             alias="formRuleEdit"
                                             :butn-type="'primary'" :show-no-right="false">
                                    <a-icon type="edit"/>
                                    {{$ti18('rxList.editBtn','编辑')}}
                                </a-menu-item>
                                <a-menu-item key="2" @click="delByIds(selectedRows)"
                                             v-if="removeEnable && selectedRowKeys.length > 0" alias="formRuleDelete"
                                             :butn-type="'danger'"
                                             :show-no-right="false">
                                    <a-icon type="delete"/>
                                    {{$ti18('rxList.delBtn','删除')}}
                                </a-menu-item>
                                <a-menu-item
                                    key="3"
                                    @click="changeExport(exportConf)"
                                    v-if="selectedRowKeys.length > 0"
                                    alias="formRuleDelete"
                                    :butn-type="'primary'"
                                    :show-no-right="false"
                                >
                                    <a-icon type="switcher"/>
                                    {{$ti18('rxList.changeExport','切换导出')}}
                                </a-menu-item>
                                <a-menu-item key="4" @click="doImport" v-if="findAuthRight('add')">
                                    <i class="iconfont icondaoru"></i>{{$ti18('rxList.importBtn','导入')}}
                                </a-menu-item>
                                <a-sub-menu>
                                    <span slot="title"><i class="iconfont icondaochu"></i>{{$ti18('rxList.exportBtn','导出')}}</span>
                                    <a-menu-item @click="doExport('1')"><i class="iconfont icondaochu"></i>{{$ti18('rxList.exportSelected','导出选中')}}
                                    </a-menu-item>
                                    <a-menu-item @click="doExport('2')"><i class="iconfont icondaochu"></i>{{$ti18('rxList.exportResults','导出查询结果')}}
                                    </a-menu-item>
                                </a-sub-menu>
                            </a-menu>
                        </a-dropdown>
                    </div>
                    <span class="search-btn-box" v-if="!isheader">
                        <span class="search-btn" @click.stop="searchshow"><i class="iconfont iconguolv"></i>{{$ti18('rxList.leachBtn','过滤')}}</span>
                    </span>
                </div>
                <div btnalign="right" slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel"
                     @close="closeSearchbar">
                    <a-form :layout="colLayout">
                        <a-row :gutter="24">
                            <a-col :span="colSpan">
                                <a-form-item :label="$ti18('rxForm.name','名称') ">
                                    <a-input :placeholder="$ti18('rxForm.name','名称','','input')" v-model="queryParam.Q_NAME__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="$ti18('rxForm.rxAlias','别名') ">
                                    <a-input :placeholder="$ti18('rxForm.rxAlias','别名','','input') " v-model="queryParam.Q_ALIAS__S_LK"/>
                                </a-form-item>
                                <a-form-item :label="$ti18('rxForm.type','类型') ">
                                    <a-select style="width: 100%" :placeholder="$ti18('rxForm.type','类型','','select')"
                                              v-model="queryParam.Q_TYPE__S_EQ">
                                        <a-select-option value="drag">{{i18n('drag','拖拽布局')}}</a-select-option>
                                        <a-select-option value="custom">{{ i18n('classical','经典布局') }}</a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan" v-if="!curApp.appId">
                                <a-form-item :label="$ti18('rxForm.appId', '应用')">
                                    <rx-search-app @change="appChange" v-model="searchApps">
                                    </rx-search-app>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
                <rx-grid
                    ref="table"
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :columns="columns"
                    :bordered="isBorder"
                    :defaultPageSize="10"
                    url="/api-form/form/core/formCustom/query"
                    :queryParam="queryParam"
                    data-field="result.data"
                    :pageSizeOptions="['10','30','40']"
                    id-field="id"
                    @selectChange="onSelectChange"
                >
                    <span slot="name" slot-scope="{ text, record }">
                        {{getName(text)}}
                    </span>
                    <span slot="exportApp">
                         {{ exportI18n('export.isExport','导出') }}
                        <export-app/>
                    </span>
                    <span slot="type" slot-scope="{ text, record }">
                        <a-tag :color="typeMap[text].color">
                            <span>{{ typeMap[text].text }}</span>
                        </a-tag>
                    </span>
                    <span slot="appId" slot-scope="{ text, record }">
                        {{allApps[text]?$i18(allApps[text].appName,'应用名称'):$ti18('rxList.noAppName','无')}}
                    </span>
                    <span slot="isExport" slot-scope="{ text, record }">
                        <a-tag :color="text == 1 ? 'green' : 'red'">
                            <span>{{ text == 1 ? exportI18n('export.yes','是') : exportI18n('export.no','否') }}</span>
                        </a-tag>
                    </span>
                    <span slot="action" slot-scope="{ text, record }" class="actionIcons">
                        <span v-if="editEnable"  @click="edit(record)">{{$ti18('rxList.editBtn','编辑')}}</span>
                        <span @click.stop="preview(record)">{{$ti18('rxList.previews','预览')}}</span>
                        <span v-if="removeEnable && record.alias!='portal' " @click="delByIds([record])">{{$ti18('rxList.delBtn','删除')}}</span>
                        <span @click.stop="deployMenu(record)" :title="$ti18('rxList.deployMenu','发布菜单')">{{$ti18('rxList.deployMenu','发布菜单')}}</span>
                        <span @click.stop="searchMenus(record.id)" :title="$ti18('rxList.searchMenus','查看发布记录')">
                            {{$ti18('rxList.searchMenus','查看发布记录')}}
                        </span>
                        <span @click.stop="viewHelp(record.id)">{{i18n('list.viewHelp','查看帮助')}}</span>
                        <span @click="setExport(record,exportConf)">{{record.isExport == 1 ? exportI18n('export.noExport','不导出') : exportI18n('export.exported','导出')}}</span>
                        <span v-if="!curApp.appId" @click="share(record)">{{$ti18('rxList.share','共享')}}</span>
                    </span>
                </rx-grid>
            </rx-fit>
        </div>
    </rx-layout>
</template>

<script>
import FormCustomApi from '@/api/form/core/formCustom'
import FormCustomEdit from './FormCustomEdit'
import {BaseList, Dialog, Util} from "@lowcode/jpaas-common-lib";
import DialogBox from "@/assets/js/DialogBox";
import RxCategoryTreeeditor from '@/components/redxun/rx-category-treeeditor'
import FormCustomHelp from './FormCustomHelp'
import changeAppJs from "@/views/modules/share/changeApp";
import {mapState} from "vuex";
import exportApp from "@/views/modules/share/exportApp";
import FormResourceShareApi from "@/api/form/core/formResourceShare";
import AppSearch from "@/views/modules/share/AppSearch";
import RxSearchApp from "@/views/modules/share/rx-search-app";
import {openUrl} from "@/utils/util";
import switchExport from "@/utils/switchExport";
import ChangeCategory from "@/views/modules/share/ChangeCategory.js"
import FormImport from "@/views/modules/form/core/FormImport.vue";

export default {
    name: 'FormCustomList',
    mixins: [BaseList,changeAppJs,AppSearch,switchExport,ChangeCategory],
    components: {
        RxCategoryTreeeditor,
        exportApp,
        RxSearchApp
    },
    computed: {
        ...mapState({
            //所属应用
            allApps: state => state.appSetting ? state.appSetting.allApps : {}
        }),
    },
    props:["currentApp"],
    data() {
        return {
            columns: [
                {
                    title: this.$ti18('rxList.index','序号'),
                    type: 'indexColumn',
                    width: 60,
                    dataIndex: 'serial',
                    scopedSlots: {customRender: 'serial'}
                },
                {title: this.$ti18('rxForm.name','名称'), dataIndex: 'name', width: 100, scopedSlots: {customRender: 'name'}},
                {title: this.$ti18('rxForm.rxAlias','别名'), dataIndex: 'alias', width: 100},
                {title: this.$ti18('rxForm.type','类型'), dataIndex: 'type', width: 100, scopedSlots: {customRender: 'type'}},
                {title: this.i18n('form.app','所属应用'), dataIndex: 'appId', width: 100, sortField: 'APP_ID_',scopedSlots: {customRender: 'appId'}},
                {
                    dataIndex: 'isExport',
                    slots: { title: 'exportApp' },
                    width: 100,
                    scopedSlots: {customRender: 'isExport'}
                },
                {title: this.$ti18('rxForm.createTime','创建时间'), dataIndex: 'createTime',  width: 120},
                {title: this.$ti18('rxList.action','操作'), width: 120,fixed:'right', dataIndex: 'action', scopedSlots: {customRender: 'action'}}
            ],
            typeMap: {
                "custom": {color: 'green', text: this.i18n('classical','经典布局')},
                "drag": {color: 'red', text: this.i18n('drag','拖拽布局')},
                "free": {color: 'yellow', text: this.i18n('free','自由布局')},
                "": {color: 'red', text: this.i18n('nothing','无')}
            },
            component: FormCustomEdit,
            zIndex:999,
            comment: this.i18n('list.customPage','页面定制'),
            statisticConfig: {
                type:"static_form",
                table:"FORM_CUSTOM t",
                field:"CATEGORY_ID_",
                whereConf:[]
            },
            /**
             * 导出配置
             */
            exportConf:{
                Api:FormCustomApi,
                id:"id"
            },
            //变更分类配置
            categoryConfig:{
                Api:FormCustomApi,
                catKey:"FORM",
                gridRef:"table"
            },
            queryData: {},
            curTree: {},
            selectedTreeId:''
        }
    },
    created() {
        this.isUserManager(this.$route.query.appId);
        this.needFilterAppId("isAppMenu");
        this.columns=this.removeAppColumn(this.curApp.appId,this.columns)
    },
    methods: {
        customAdd(){
            let self_=this;
            Util.open({
                component:FormCustomEdit ,
                curVm: this,
                zIndex:999,
                max:true,
                title:  self_.i18n('list.customPage','页面定制'),
                data: {
                    categoryId:this.selectedTreeId
                },
            }, function (action) {
                if (action == "ok") {
                    self_.refreshGrid();
                }
            })
        },
        getName(name){
            let lan = Util.getLanguage();
            if(typeof name === 'string'){
                if(name.includes('zh-CN') > -1){
                    try {
                        let o =new Function(`return ${name}`)()
                        return o[lan] ?? name
                    }catch (e) {
                        return name
                    }
                }
                return name
            }else if(Util.getObjType(name) === 'object'){
                return name[lan]
            }
            return name
        },
        i18n(name, text, key) {
            return this.$ti18(name, text, "formCustom", key);
        },
        //资源共享
        share(record){
            let self=this;
            FormResourceShareApi.getShareApps(record.id).then(res => {
                let initData=res.data;
                if(!initData){
                    initData=[];
                }
                self.showAppDialog(initData,record.id,record.alias,record.name);
            });
        },
        showAppDialog(initData,resId,resKey,resName){
            Dialog.openSystemAppDialog({
                curVm: this, widthHeight: ['1150px', '735px'],
                data:{initSelected: initData,isDevelopApp:true,isSelectApp:true}
            }, function (self, data) {
                //保存共享信息
                FormResourceShareApi.saveShareApps(data.apps,resId,resKey,resName,"5").then(res => {
                    if (res.success && res.code == 200) {
                    }
                });
            })
        },
        exportI18n(name,text,key){
            return this.$ti18(name,text,"appExport",key);
        },
        delById(ids) {
            return FormCustomApi.del({ids: ids.join(',')});
        },
        getListByParams(parameter) {
            return FormCustomApi.query(parameter)
        },
        deployMenu(record) {
            var component = "modules/form/FormCustomView/FormCustomView";
            DialogBox.openDeploymenuDialog({
                releaseId: record.id,
                name: record.name,
                key: record.alias + 'Custom',
                component: component,
                params: {alias: record.alias},
                curAppObj:this.curApp,
            }, {
                curVm: this, widthHeight: ['800px', '600px']
            })
        },
        searchMenus(releaseId) {
            var config = {
                curVm: this,
                data: {
                    releaseId: releaseId,
                },
            }
            DialogBox.openMenuReleaseDialog(config)
        },
        search() {
            this.$refs.table.loadData();
        },
        cancel(){
            this.resetSearch();
        },
        closeSearchbar() {
            //关闭过滤弹窗；（点击X触发）
            this.fitSearch = false;
        },
        getLangText(text){
            let lan = Util.getLanguage();
            if(text.includes("{") && text.includes("}")){
                try {
                    let obj = new Function(`return ${text}`)();
                    return obj[lan]
                }catch (e) { }
            }
            return text
        },
        preview(record) {
            let appKey= this.currentApp.clientCode;
            if(!appKey){
                return;
            }
            let appId=record.appId;
            let ctxPath= process.env.VUE_APP_CONTEXT_MAIN;
            let url=`${ctxPath}/FormCustomView/${record.alias}?appId=${appId}`;
            let title=this.getLangText(record.name);
            openUrl({url:url,title:title,curVm:this,max:true});
        },
        handSelect(curRow) {
            this.curTree = curRow;
            var treeId = curRow.treeId;
            this.selectedTreeId = treeId;
            let params={
                Q_CATEGORY_ID__S_EQ:""
            }
            if(treeId!="0"){
                params.Q_CATEGORY_ID__S_EQ=treeId;
            }else {
                params.Q_CATEGORY_ID__S_EQ="";
            }
            this.loadData(params);
        },
        delByIds(records) {
            if(!records || records.length==0){
                this.$message.warn(this.i18n('noSelection','没有选择记录!'));
                return;
            }
            let self_=this;
            this.$confirm({
                title: self_.$ti18('rxMsa.actionTips','操作提示'),
                content: self_.$ti18('rxMsa.delInfo','您确定需要删除选中的记录吗？'),
                okText: self_.$ti18('rxForm.ackBtn','确认'),
                cancelText: self_.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    var ids=[];
                    for (var i = 0; i < records.length; i++) {
                       ids.push(records[i].id);
                    }
                    FormCustomApi.del({ids: ids.join(',')}).then(res => {
                        self_.$refs[self_.table].loadData();
                    })
                },
                onCancel() {}
            })
        },
        viewHelp(id){
            var baseConf = {
                curVm: this,
                widthHeight: ['1000px', '600px'],
                zIndex: 99999,
                component: FormCustomHelp,
                title: this.i18n('list.pageHelp','页面定制帮助'),
                data:{
                    pkId:id
                }
            };
            Util.open(baseConf, function (action) {
                if (action != 'ok') return;
            })
        },
        changeAppId(selectedRows){
            FormCustomApi.saveList(selectedRows);
        },
        doImport() {
            if (!this.curTree || !this.curTree.treeId) {
                this.$warning({
                    title: this.$ti18('rxMsa.masWarn.delInfo','警告'),
                    content: this.i18n("form.formClass",'请选择表单分类！',"select"),
                });
                return
            }
            var treeId = this.curTree.treeId;
            let self_ = this;
            Util.open(
                {
                    component: FormImport,
                    curVm: this,
                    widthHeight: ['800px', '600px'],
                    title: this.i18n("form.pageImport","自定义页面导入"),
                    data: {
                        treeId: treeId,
                        callback: function (params) {
                            let self = this;
                            FormCustomApi.doImport(params).then(res => {
                                this.isSpinning = false;
                                if (!res.success) {
                                    self.$confirm({
                                        title: self.$ti18('rxMsa.masWarn.delInfo','警告'),
                                        content: self.$comi18('SysApp.appImport.importFailed', '导入失败！'),
                                        cancelText: self.$ti18('rxForm.cancelBtn','取消')
                                    });
                                    return;
                                }
                                self.getUpdataSqls(res.data);
                                self_.$refs.table.loadData();
                            });
                        }
                    }
                }, function (action) {
                }
            );
        },
        doExport(isSelected) {
            var exportList = [];
            //选中的导出
            if (isSelected == "1") {
                exportList = this.$refs.table.getSelectedRows();
                if (!exportList || exportList.length == 0) {
                    this.$warning({
                        title: this.$ti18('rxMsa.masWarn.delInfo','警告'),
                        content: this.$comi18('bpmDef.selectRecord','请选择需要导出的记录！'),
                    });
                    return;
                }
                let ids = []
                exportList.forEach((item) => {
                    ids.push(item.id)
                })
                this.queryData.params = {
                    ids: ids.toString()
                }
            } else {
                // 导出所查询的
                this.queryData.params = {
                    isQuery: 0,
                }
                this.queryData.params = Object.assign(this.queryData.params, this.queryParam)
            }
            if (this.$refs.table.dataAction == "") {
                this.$warning({
                    title:this.$ti18('rxMsa.masWarn.delInfo','警告'),
                    content: this.i18n('form.noData','该分类没有数据！'),
                });
                return;
            }
            FormCustomApi.listExport(this.queryData)
        },
    }
}
</script>
<style scoped>

</style>

